<script setup lang="ts">
import { resize, convert, compress } from '/@/api/services/WaterMark'
import UploadItem from './uploadItem.vue'

let title = ''
let modal1 = false
let choose = ref<string>('1')
let file1 = ref({

})
let has_file = ref<boolean>(false)
let format = 'png'
let value = 1
let quality = 100
let marks1 = {
  70: '70%',
  80: '80%',
  90: '90%',
  100: {
    style: {
      color: '#ff0000',
    },
    label: '原图',
  },
}
let marks = ref({
  0.95: '95%',
  1.1: '110%',
  0.9: '90%',
  1: {
    style: {
      color: '#ff0000',
    },
    label: '原图',
  },
})
let format1 = ['jpg', 'jpeg', 'png']
let isCollapsed = ref<boolean>(false)
let BASE_URL = 'http://101.34.204.110:5000/static/'
let loadingStatus = ref<boolean>(false)
let encodedImg = ref<any>(null)
let returnedImgLink = ''
let originImageLink = ''
// returnedImgLink: 'http://101.34.204.110:5000/static/img_resize_ratiob6NaD.jpg',
// originImageLink: "http://101.34.204.110:5000/static/img_resize_ratiob6NaD.jpg",
let decodeLoadingStatus = ref<boolean>(false)
let returntxt = ref<string>('sa')

let closeimg = () => {
  encodedImg = null
}
import { ElNotification } from 'element-plus'
// import
let handleFormatError = (file: { name: string }, desc: string) => {
  ElNotification.warning({
    title: '文件格式不正确',
    message:
      'File format of ' + file.name + ' is incorrect, please select ' + desc
  })
}

let handleMaxSize = (file: { name: any; size?: number; type?: any; }, desc: string) => {
  ElNotification.warning({
    title: '文件大小超出范围',
    message: 'File  ' + file.name + ' is too large, no more than ' + desc
  })
}
// import { ElLoading } from 'element-plus'
// let loadingInstance = ElLoading.service({ fullscreen: true })

let upload = () => {
  if (!encodedImg) {
    ElNotification.error({
      title: '请上传图片',
      message: '加密需要图片和加密信息才能加密 ',
    })
    return
  }

  let fileReader = new FileReader()
  fileReader.readAsDataURL(encodedImg)
  fileReader.onload = event => {
    originImageLink = event.target.result
  }
  if (choose === '1') {
    decodeLoadingStatus = true

    resize(encodedImg, value)
      .then(result => {
        title = '缩放' + that.value + ' 攻击'
        console.log(result)
        modal1 = true
        // that.returntxt = result.text
        // that.originImageLink = that.encodedImg

        // that.encodedImg = null;
        returnedImgLink = BASE_URL + result.img_path
        console.log(returnedImgLink)
        // that.$Spin.hide()
        decodeLoadingStatus = false
      })
      .catch(error => {
        // that.$Spin.hide()
        decodeLoadingStatus = false
        ElNotification.error({
          title: '错误',
          message: error,
        })
      })
  }
  if (choose === '2') {
    decodeLoadingStatus = true
    // this.$Spin.show()
    convert(encodedImg, format)
      .then(result => {
        title = '格式转换 -> ' + that.format
        console.log(result)
        modal1 = true
        // that.originImageLink = that.encodedImg
        // that.returntxt = result.text
        // that.encodedImg = null;
        returnedImgLink = BASE_URL + result.img_path
        console.log(that.returnedImgLink)
        // that.$Spin.hide()
        decodeLoadingStatus = false
      })
      .catch(error => {
        // that.$Spin.hide()
        decodeLoadingStatus = false
        ElNotification.error({
          title: '错误',
          message: error,
        })
      })
  }

  if (choose === '3') {
    decodeLoadingStatus = true
    // this.$Spin.show()
    // let that = this
    compress(encodedImg, quality)
      .then(result => {
        title = '图片压缩 -> ' + format
        console.log(result)
        modal1 = true
        // that.originImageLink = that.encodedImg
        // that.returntxt = result.text
        // that.encodedImg = null;
        returnedImgLink = BASE_URL + result.img_path
        console.log(returnedImgLink)
        // that.$Spin.hide()
        decodeLoadingStatus = false
      })
      .catch(error => {
        decodeLoadingStatus = false
        ElNotification.error({
          title: '错误',
          message: error,
        })
      })
  }
}

let decodeUpload = (file: { name: string; size: number; type: any; }) => {
  /**
   * 解码器上传
   */
  // 验证
  if (!/\.(jpg|jpeg|png)$/.test(file.name)) {
    handleFormatError(file, 'jpg,png')
    return false
  }
  if (file.size > 1024 * 200) {
    handleMaxSize(file, '200kb')
    return false
  }
  encodedImg = file
  file1 = {
    size: (file.size / 1024).toFixed(2) + 'kb',
    name: file.name,
    type: file.type,
  }
  has_file = true
  return false
}

let getUrlname = (url) => {
  //假如传进来的url是 http://www.qq.com/index.html?name=joey 这里一共是有3个斜杠,如果我们想获取index.html
  url = url.split('?')[0] // 我们只要?号前的
  let urlSlashCount = url.split('/').length // 统计有3斜杠
  return url.split('/')[urlSlashCount - 1].toLowerCase() //获取数组最后一个
}

let download = () => {
  // console.log("下载")
  let image = new Image()
  let name = getUrlname(returnedImgLink)
  image.setAttribute('crossOrigin', 'anonymous')
  image.onload = function() {
    let canvas = document.createElement('canvas')
    canvas.width = image.width
    canvas.height = image.height
    let context = canvas.getContext('2d')
    context.drawImage(image, 0, 0, image.width, image.height)
    let url = canvas.toDataURL('image/jpeg') //得到图片的base64编码数据
    let a = document.createElement('a') // 生成一个a元素
    let event = new MouseEvent('click') // 创建一个单击事件
    a.download = name || 'photo' // 设置图片名称
    a.href = url // 将生成的URL设置为a.href属性
    a.dispatchEvent(event) // 触发a的单击事件
  }

  image.src = returnedImgLink
}
let decodeContent = computed(() => {
  //this.commend.content是后端传回来的文本数据，就是要对这个数据进行处理
  let arr = returntxt.split('')
  return arr
    .map(item => {
      return item === '\n' ? '<br>' : item
    })
    .join('')
})
</script>

<template>
  <div class="con">
    <UploadItem
      v-if="!encodedImg"
      :file="encodedImg"
      step="step 1"
      name="请上传隐写图"
      :format="format1"
      @before-upload="decodeUpload"
    ></UploadItem>

    <div v-if="has_file">
      <ul class="onlineuploader-items-list">
        <li v-if="encodedImg" class="onlineuploader-item">
          <el-row>
            <el-col span="1">
              <div class="onlineuploader-item-image">
                <div class="image1"></div>
              </div>
            </el-col>
            <el-col span="6" class="column-title">
              <div>{{ file1.name }}</div>
              <span>{{ file1.size }}</span>
            </el-col>
            <el-col span="3" class="center">
              {{ file1.type }}
            </el-col>
            <el-col span="1" :offset="13" @click="closeimg">
              <div class="wrong"></div>
            </el-col>
          </el-row>
        </li>
      </ul>
    </div>

    <el-tabs v-model="choose" class="tab" type="card">
      <el-tab-pane label="缩放攻击" name="1">
        <div>请选择缩放比例</div>
        <el-slider
          v-model="value"
          show-input
          :min="0.9"
          :max="1.1"
          :step="0.01"
          :marks="marks"
        ></el-slider>
      </el-tab-pane>
      <el-tab-pane label="格式转换" name="2">
        <el-radio-group v-model="format">
          <el-radio label="png" border></el-radio>
          <el-radio label="bmp" border></el-radio>
        </el-radio-group>
      </el-tab-pane>

      <el-tab-pane label="图片压缩" name="3">
        <div>请选择缩放比例</div>
        <el-slider
          v-model="quality"
          show-input
          :min="70"
          :max="100"
          :step="1"
          :marks="marks1"
        ></el-slider>
      </el-tab-pane>
    </el-tabs>

    <el-space direction="vertical" type="flex">
      <Button type="success" long @click="upload">开始攻击</Button>
    </el-space>

    <el-main
      v-model="modal1"
      draggable
      scrollable
      :title="title"
      ok-text="下载图片"
      @on-ok="download"
    >
      <el-descriptions :col="1" layout="vertical" class="des">
        <el-descriptions-item term="原图(左) 攻击后(右): ">
          <el-row class="ivu-text-center" :gutter="24">
            <el-col flex="1">
              <img class="up" :src="originImageLink" />
              <el-pagination class="ivu-mt">原图</el-pagination>
            </el-col>
            <el-col flex="1">
              <img class="up" :src="returnedImgLink" />
              <el-pagination class="ivu-mt">攻击后</el-pagination>
            </el-col>
          </el-row>
        </el-descriptions-item>
      </el-descriptions>
    </el-main>
  </div>
</template>

<style scoped>
.con {
  margin: 0 auto;
}
.tab {
  min-height: 200px;
  height: 100%;
  width: 100%;
  padding: 20px;
}

.wrong {
  background-image: url('../../assets/wrong.svg');
  background-repeat: no-repeat;
  background-size: 50% 50%;
  /*background-color: red;*/
  width: 100%;
  height: 100%;
  /*background: #259229;*/
  background-position: center;
}

.up {
  height: 100%;
  width: 100%;
}

.des {
  margin-bottom: 20px;
}

.onlineuploader-items-list {
  display: block;
  margin: 0px;
  padding: 0;
  list-style: none;
  /*border: 1px solid #ebeef1;*/
  cursor: pointer;
  box-shadow: 0 1px 2px 0 rgb(60 64 67 / 30%), 0 1px 3px 1px rgb(60 64 67 / 15%);
  border-radius: 0.625rem;
  border: 1px solid transparent;
  transition: box-shadow 0.4s, transform 0.4s;
}

.onlineuploader-items-list:hover {
  border: 1px solid #2b932f;
  transform: translateY(-2%);
}

.onlineuploader-item {
  position: relative;
  margin: 0;
  padding: 5px 16px 5px 22px;
  border-bottom: 1px solid #ebeef1;
  /*border-top: 1px solid #ebeef1;*/
}

.column-title {
  padding-left: 16px;
  padding-right: 16px;
  color: #555;
  overflow: hidden;
}

.column-title div {
  width: 100%;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  font-weight: 400;
  text-shadow: 0 1px 0 rgb(0 0 0 / 15%) !important;
}

.column-title span {
  font-size: 12px;
  color: #979fb8;
  opacity: 0.7;
  font-weight: 300;
}

.onlineuploader-item-image {
  display: flex;
  height: 100%;
  width: 100%;
}

.onlineuploader-item-image div {
  /*position: absolute;*/
  /*top: 0;*/
  /*left: 0;*/
  width: 32px;
  height: 32px;
  /*flex: 1;*/
  margin: auto;
  border-radius: 3px;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-position: center;
  /*box-shadow: 0 2px 5px 0 rgb(147 147 147 / 64%);*/
}

.image1 {
  background-image: url('../assets/JPG_1.svg');
}

.text {
  overflow: auto;
  max-height: 150px;
}
</style>
